package com.ax.center.service.impl;

import com.ax.center.dto.ApiResponse;
import com.ax.center.entity.Role;
import com.ax.center.mapper.RoleMapper;
import com.ax.center.service.RoleAuthService;
import com.ax.center.service.RoleService;
import com.ax.center.service.UserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zy
 * @date 2023/7/5 16:25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleAuthService roleAuthService;

    @Autowired
    private UserRoleService userRoleService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse deleteRole(Long roleId) {
        try {
            roleMapper.deleteById(roleId);
            roleAuthService.deleteOneByRoleId(roleId);
            userRoleService.deleteOneByRoleId(roleId);
            return ApiResponse.ok("删除角色成功");
        } catch (Exception e) {
            return ApiResponse.fail("删除角色失败");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse addRole(Role role) {

        Long roleId = role.getRoleId();
        if (query().eq("id",roleId).count()>0) {
            return ApiResponse.fail("角色已存在,添加失败");
        }
        List<Long> permissions = role.getPermissions();
        roleAuthService.insertMore(roleId,permissions);
        boolean save = save(role);
        if (Boolean.FALSE==save) {
            return ApiResponse.fail("新增成功");
        }else{
            return  ApiResponse.ok("新增成功");
        }
    }

    @Override
    public ApiResponse queryAll() {
        List<Role> list = query().list();
        return ApiResponse.ok(list);
    }


}
